//
//  MasCampsTableDataViewController.m
//  PartyAnimal
//
//  Created by Hilary Muludiang on 3/17/12.
//  Copyright 2012 Muludiang. All rights reserved.
//

#import "MasCampsTableDataViewController.h"
#import "StackMob.h"
#import "AddMasCampViewController.h"
#import "iBacchanal.h"
#import "MasCampsDetailViewController.h"
#import "PartyAnimalAppDelegate.h"
#import "UIImageView+AFNetworking.h"


@implementation MasCampsTableDataViewController

@synthesize tableData;
@synthesize masCampTable;
@synthesize carnivalYears;
@synthesize masCampsDetailViewController;




-(void)reachabilityChanged:(NSNotification *)note{
	
	Reachability* curReach = [note object];
	NSParameterAssert([curReach isKindOfClass: [Reachability class]]);

	NetworkStatus netStatus = [curReach currentReachabilityStatus];
	iBacchanal *bacchanal = [iBacchanal sharedUser];
	switch (netStatus){
		case NotReachable:{
			//show an alert to let the user know that they can't connect...
			UIAlertView *alert = [[[UIAlertView alloc] initWithTitle: nil message: bacchanal.downMessage
															delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK", nil] autorelease];
			[alert show];
			bacchanal.networkUp = NO;

			break;
		}
		default:{
			// Network is reachable
			UIAlertView *alert = [[[UIAlertView alloc] initWithTitle: nil message: bacchanal.upMessage
															delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK", nil] autorelease];
			[alert show];
			[self refreshMasBandsData];	
			bacchanal.networkUp = YES;

			break;
		}
			
    }
}



#pragma mark AlertView delegate methods
//- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
//    [alertView release];
//}

-(void)refreshMasBandsData{
	// set query depth
	
	iBacchanal *bacchanal = [iBacchanal sharedUser];

	if (bacchanal.dataChanged || bacchanal.masBandsData == nil){
		StackMobQuery *q = [StackMobQuery query];
	[q setExpandDepth:4];
	
	[[StackMob stackmob] get:@"mascamps" withQuery:q andCallback:^(BOOL success, id result) {
		if (success) {
			bacchanal.masBandsData = [[NSMutableArray alloc] initWithArray:result];
			//NSLog(@"Source data: %@", bacchanal.masBandsData);
			[self buildTable];
			[masCampTable reloadData];
			// object found, cast result to NSArray* and continue with processing
		} else {
			// unable to retrieve object, cast result to NSError* and inspect code & message
			NSLog(@"Error: %@", result);
		}
	}];
	}
	
	
}

-(void)buildTable{
	
	iBacchanal *bacchanal = [iBacchanal sharedUser];
	
	carnivalYears = [[NSMutableArray alloc] init];
	tableData = [[NSMutableArray alloc] init];
	
	NSMutableArray *temp = [[NSMutableArray alloc] init];
	for (NSDictionary *camp in bacchanal.masBandsData){
		[temp addObject:[camp objectForKey:@"carnivalyear"]];
	}
	carnivalYears = [[[[NSSet setWithArray:temp] allObjects] sortedArrayUsingSelector:@selector(compare:)]retain];
	
	temp = [[NSMutableArray alloc] init];
	
	for (NSString *year in carnivalYears){
		NSMutableArray *camps = [[NSMutableArray alloc] init];
		for (NSDictionary *camp in bacchanal.masBandsData){
			if ([[camp objectForKey:@"carnivalyear"] isEqualToString: year]){
				[camps addObject:camp];
			}
		}
		//NSLog(@"Camps: %@", camps);
		[tableData addObject: camps];
		[camps release];
	}
	//NSLog(@"temp Camps: %@", temp);
	[temp release];
}


-(IBAction)addMasCamp:(UIButton *)sender{
	
	iBacchanal *bacchanal = [iBacchanal sharedUser];
	if (bacchanal.loggedIn){
	
	AddMasCampViewController *addMasCampViewController = [[AddMasCampViewController alloc] initWithNibName:@"AddMasCamp" bundle:nil];
	UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:addMasCampViewController];
	[addMasCampViewController release];
	
	navController.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
	[self presentModalViewController:navController animated:YES];
	[navController release];
	}
	else{
		UIAlertView *msg = [[UIAlertView alloc] initWithTitle:nil message:@"You must be logged in to submit a Mas Band. Tap on the \"Account\" Tab to log in or create an account" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
		[msg show];
		[msg release];
	}
	
}


#pragma mark -
#pragma mark Initialization

/*
 - (id)initWithStyle:(UITableViewStyle)style {
 // Override initWithStyle: if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
 self = [super initWithStyle:style];
 if (self) {
 // Custom initialization.
 }
 return self;
 }
 */


#pragma mark -
#pragma mark View lifecycle


- (void)viewDidLoad {
    [super viewDidLoad];
	
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
	
	//NSLog(@"Mas Camp Table");
	self.navigationItem.title = @"Mas Camps";
	
	//self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc] initWithTitle:@"Cities" style:UIBarButtonItemStylePlain target:self action:@selector(switchViews:)] autorelease];
	self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc]  initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(addMasCamp:)] autorelease];
}


/*
 - (void)viewDidAppear:(BOOL)animated {
 [super viewDidAppear:animated];
 
 }*/


- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
	iBacchanal *bacchanal = [iBacchanal sharedUser];
	if (bacchanal.networkUp){
		[self refreshMasBandsData];
		self.navigationItem.rightBarButtonItem.enabled = YES;
	}
	else
		self.navigationItem.rightBarButtonItem.enabled = NO;
	
	[[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(reachabilityChanged:) name: kReachabilityChangedNotification object: nil];
	

	
}

/*
 - (void)viewWillDisappear:(BOOL)animated {
 [super viewWillDisappear:animated];
 }
 */

 - (void)viewDidDisappear:(BOOL)animated {
 [super viewDidDisappear:animated];
 	 [[NSNotificationCenter defaultCenter] removeObserver:self];
 }
 
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations.
    return YES; // (interfaceOrientation == UIInterfaceOrientationPortrait);
}


#pragma mark -
#pragma mark Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return [carnivalYears count];
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    return [[tableData objectAtIndex:section]count];
}


// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }
    
    // Configure the cell...
    [[cell textLabel] setText:[[[tableData objectAtIndex:indexPath.section] objectAtIndex: indexPath.row] objectForKey: @"mascampname"]];
	
	NSURL *url = [NSURL URLWithString:[[[tableData objectAtIndex:indexPath.section] objectAtIndex: indexPath.row] objectForKey: @"mascamplogo"] ];
	UIImageView *testView = [[UIImageView alloc] init];
	[testView setImageWithURL:url];
	[[cell imageView] setImage: testView.image ];
	
	return cell;
}

-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
	return [carnivalYears objectAtIndex:section];
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
	/*NSCharacterSet *nonNumberSet = [[NSCharacterSet characterSetWithRange:NSMakeRange('0',10)] invertedSet];
	 NSString *trimmed = [[cell textLabel].text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
	 BOOL isNumeric = trimmed.length > 0 && [trimmed rangeOfCharacterFromSet:nonNumberSet].location == NSNotFound;
	 NSString *temp = [NSString stringWithFormat:@"%@ (Done)",[cell textLabel].text ];*/
	
	cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
	
	/*if ((isNumeric) && [[cell textLabel].text intValue] < 2012){
	 [[cell textLabel] setTextColor:[UIColor redColor]];
	 [[cell textLabel] setText:temp];	
	 }
	 else{
	 [[cell textLabel] setTextColor:[UIColor blackColor]];
	 }*/
	
}
/*
 // Override to support conditional editing of the table view.
 - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
 // Return NO if you do not want the specified item to be editable.
 return YES;
 }
 */


/*
 // Override to support editing the table view.
 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
 
 if (editingStyle == UITableViewCellEditingStyleDelete) {
 // Delete the row from the data source.
 [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
 }   
 else if (editingStyle == UITableViewCellEditingStyleInsert) {
 // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
 }   
 }
 */


/*
 // Override to support rearranging the table view.
 - (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
 }
 */


/*
 // Override to support conditional rearranging of the table view.
 - (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
 // Return NO if you do not want the item to be re-orderable.
 return YES;
 }
 */


#pragma mark -
#pragma mark Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // Navigation logic may go here. Create and push another view controller.
    /*
	 <#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:@"<#Nib name#>" bundle:nil];
     // ...
     // Pass the selected object to the new view controller.
	 [self.navigationController pushViewController:detailViewController animated:YES];
	 [detailViewController release];
	 */
	
	MasCampsDetailViewController *masCampsDetailView = [[MasCampsDetailViewController alloc] initWithNibName:@"MasCampsDetail" bundle:nil];
	self.masCampsDetailViewController = masCampsDetailView;
	
	iBacchanal *bacchanal = [iBacchanal sharedUser];
	bacchanal.masBandID = [[[tableData objectAtIndex:indexPath.section] objectAtIndex: indexPath.row] objectForKey: @"mascamps_id"];
	//event.eventID = [[[eventsTableData objectAtIndex:indexPath.section] objectAtIndex:indexPath.row] objectForKey:@"events_id"];
	
	[self.navigationController pushViewController:masCampsDetailView animated:YES];
	[masCampsDetailViewController release];
	
	//Reuse NavController
	PartyAnimalAppDelegate *delegate = [[UIApplication sharedApplication] delegate];
	[delegate.partyAnimalNavigatorViewController pushViewController:masCampsDetailViewController animated:YES];
	
	
}


#pragma mark -
#pragma mark Memory management

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Relinquish ownership any cached data, images, etc. that aren't in use.
}

- (void)viewDidUnload {
    // Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.
    // For example: self.myOutlet = nil;
}


- (void)dealloc {
	[masCampsDetailViewController release];
	[carnivalYears release];
	[tableData release];
	[masCampTable release];
    [super dealloc];
}


@end

